//
//  GestureView.m
//  GestureTest
//
//  Created by 迷你金服 on 2017/3/9.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "GestureView.h"
#import "Masonry.h"
#import "UserDefaultsTool.h"
#define BtnSizeWH [UIScreen mainScreen].bounds.size.width/7
#define BtnTopMargin [UIScreen mainScreen].bounds.size.height/3
@interface GestureView()

/* 手指位置 */
@property (assign, nonatomic) CGPoint fingerPoint ;

/* 第一个button */
@property (strong, nonatomic) UIButton *firstButton;

/* 绘制线条的颜色*/
@property (strong, nonatomic) UIColor *lineColor;
@end
@implementation GestureView
- (void)awakeFromNib {
    [super awakeFromNib];
    [self setupUI];
    self.selectBtnArr = [[NSMutableArray alloc]initWithCapacity:0];
    self.lineColor = [UIColor colorWithRed:197/255.0 green:244/255.0 blue:255/255.0 alpha:1.0];
    
}
- (instancetype)initWithFrame:(CGRect)frame {

    if (self = [super initWithFrame:frame]) {
        
        [self setupUI];
        
    }
    return self;
}

#pragma mark -搭建界面

- (void)setupUI {
    
//    self.backgroundColor = [UIColor whiteColor];
    self.selectBtnArr = [[NSMutableArray alloc]initWithCapacity:0];
    CGFloat btnMargin = ([UIScreen mainScreen].bounds.size.width - 5*BtnSizeWH)/2;
    for (int i = 0; i < 9; i++) {
        int row = i/3;
        int cloum = i%3;
        //循环创建9个按钮并布局
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake((BtnSizeWH+btnMargin)*row+BtnSizeWH, (BtnSizeWH+btnMargin)*cloum, BtnSizeWH, BtnSizeWH)];
        //把按钮设置为圆形
        [btn.layer setCornerRadius:BtnSizeWH*0.5];
        
        btn.layer.masksToBounds = YES;
        btn.userInteractionEnabled = NO;
        [btn setImage:[UIImage imageNamed:@"gesture_gray_dot"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"gesture_blue_dot"] forState:UIControlStateSelected];
        btn.tag = i+1;
        [self addSubview:btn];
    }
    
}

#pragma mark -绘制

- (void)drawRect:(CGRect)rect {
    
    //如果没有触摸到按钮，不做任何操作
    if (self.selectBtnArr.count == 0) {
        return;
    }
    //绘制
    UIBezierPath *path = [UIBezierPath bezierPath];
    path.lineWidth = 1.f;
    [self.lineColor set];

    
    
        for (UIButton *btn in self.selectBtnArr) {
        //第一个按钮为起始点
        if (btn == self.selectBtnArr.firstObject) {
            [path moveToPoint:btn.center];
        }else {
            [path addLineToPoint:btn.center];
        }
    }
    //绘制到最后结束按钮的位置
    [path addLineToPoint:_fingerPoint];
    //渲染
    [path stroke];
}

#pragma mark -touch
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //取到触摸点的位置
    UITouch *touch = [touches anyObject];
    [self doSomethingWithTouch:touch];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //取到触摸点的位置
    UITouch *touch = [touches anyObject];
    [self doSomethingWithTouch:touch];
 
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //结束按钮位置
    UIButton *btn = self.selectBtnArr.lastObject;
    _fingerPoint = btn.center;
    //取到保存的密码
    NSString *savePassword = [UserDefaultsTool objectForKey:kGesturePassword];
    //获取输入的结果
    NSMutableString *result = [[NSMutableString alloc]initWithCapacity:0];
    for (int i = 0; i < self.selectBtnArr.count; i++) {
        UIButton *button = self.selectBtnArr[i];
        [result appendFormat:@"%d", (int)button.tag];
    }
    _password = result;
    if(savePassword.length > 0 && _isReset == NO) {//有密码就比较
        if ([result isEqualToString:savePassword] || [result isEqualToString:_resetPasswordStr]) {//密码正确
            [self.delegate gestureLockPasswordRight:self];
            [self resetView];
        }else {//密码错误
            [self.delegate gestureLockPasswordError:self];
            [self resetPasswordErrorView];
        }
    }else {//无密码就去设置密码
        [self.delegate gestureLockSetPassword:(NSString *)result gestureView:self];
        
        [self resetView];
    }
//    [self resetView];
}

#pragma mark -处理触摸

- (void)doSomethingWithTouch:(UITouch *)touch {

    CGPoint point = [touch locationInView:self];
    _fingerPoint = point;
    //遍历所有button，判断是否触摸到
    for (UIButton *oneButton in self.subviews) {
        if (CGRectContainsPoint(oneButton.frame, point)) {
            oneButton.selected = YES;
            if (![self.selectBtnArr containsObject:oneButton]) {
                //记录
                [self.selectBtnArr addObject:oneButton];
            }
        }
    }
    //通知重新绘制.刷新界面
    [self setNeedsDisplay];
}

//触摸结束恢复原样
- (void)resetView {
    
    for (UIButton *button in self.selectBtnArr) {
        button.selected = NO;
    }
    [self.selectBtnArr removeAllObjects];
    [self setNeedsDisplay];
}

//触摸结束恢复原样
- (void)resetPasswordErrorView {
    for (UIButton *button in self.selectBtnArr) {
        [button setImage:[UIImage imageNamed:@"gesture_red_dot"] forState:UIControlStateSelected];
        self.lineColor = [UIColor colorWithRed:244/255.0 green:196/255.0 blue:208/255.0 alpha:1.0];
        [self setNeedsDisplay];
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        for (UIButton *button in self.selectBtnArr) {
            button.selected = NO;
            [button setImage:[UIImage imageNamed:@"gesture_blue_dot"] forState:UIControlStateSelected];
              self.lineColor = [UIColor colorWithRed:197/255.0 green:244/255.0 blue:255/255.0 alpha:1.0];
        }
        [self.selectBtnArr removeAllObjects];
        [self setNeedsDisplay];

        
    });
}

- (void)savePassword:(NSString *)password {
    
    [UserDefaultsTool saveObject:password forKey:kGesturePassword];
    //记录
    _password = password;
    //保存

}


@end
